import React, { useEffect } from 'react';
import styles from './index.less';
import addTacticSvg from '@/assets/InterprovincialSpotDeclaration/add_tactic.svg';
import deleteTacticSvg from '@/assets/InterprovincialSpotDeclaration/tactic_delete.svg';
import { NEW_TACTIC_OPTIONS } from '../../constant';
import { Select } from 'antd';
import { useSetState } from 'ahooks';
import { TJModel } from '@/pages/ETrade/components';
import { connect } from 'umi';
import _ from 'lodash';
import { TRAlert } from '#/components';
import { PlusOutlined } from '@ant-design/icons';
const TacticPage = ({
  children,
  title = '',
  index,
  planData,
  dispatch,
  activeKey,
  type,
  date,
  disabled = false,
  hourOrder = '',
}) => {
  const [state, setState] = useSetState({
    visible: false,
    tacticType: undefined,
    tacticName: '',
    options: [],
  });
  const deleteTacticFun = async () => {
    const res = await TRAlert.show('当前策略信息将被删除,是否继续');
    if (res.index === 1) {
      let data = _.cloneDeep(planData);
      let arr = data[+activeKey]['strategyList'] || [];
      arr.splice(index, 1);
      data[+activeKey]['strategyList'] = arr;
      // 删除策略重置表格勾选
      dispatch({
        type: 'interprovincialSpotDeclaration/setState',
        payload: {
          planData: data,
          selectRowsObj: {},
        },
      });
    }
  };

  useEffect(() => {
    if (state.visible) {
      let t1Count = 1;
      let t2Count = 1;
      let t3Count = 1;
      const data = _.cloneDeep(planData[+activeKey]) || {};
      data?.strategyList?.forEach((i) => {
        const { strategyName = '' } = i;
        let count = strategyName ? strategyName?.split('-')?.[1] : 1;
        count = count ? +count + 1 : 1;
        switch (i.strategyType) {
          case 1:
            t1Count = count > t1Count ? count : t1Count;
            break;
          case 2:
            t2Count = count > t2Count ? count : t2Count;
            break;
          case 3:
            t3Count = count > t3Count ? count : t3Count;
            break;
        }
      });
      const options = NEW_TACTIC_OPTIONS.map((i) => {
        switch (i.value) {
          case 1:
            return {
              label: i.label + t1Count,
              value: 1,
            };
          case 2:
            return {
              label: i.label + t2Count,
              value: 2,
            };
          case 3:
            return {
              label: i.label + t3Count,
              value: 3,
            };
        }
      });
      setState({
        options,
      });
    }
  }, [state.visible]);

  // 打开新增策略弹窗
  const changeVisible = () => {
    setState({
      visible: !state.visible,
      tacticType: undefined,
      tacticName: '',
    });
  };

  const tacticTypeChange = (_, v) => {
    setState({
      tacticType: v.value,
      tacticName: v.label,
    });
  };

  const addTacticFun = () => {
    if (!state.tacticType) {
      return;
    }
    const obj = {
      strategyType: state.tacticType,
      strategyName: state.tacticName,
      electricEnergy: 1,
      electricPriceType: 1,
      details: [],
    };
    const data = _.cloneDeep(planData);
    // 日内的情况下，把查询选择的时间段添加到markDate字段
    if (type === 'intraday') {
      obj.markDate = date;
    }
    if (type === 'dayahead') {
      // 日前
      const lineData = {
        startOrder: '0015',
        endOrder: '2400',
        timePeriod: '0015-2400',
        electricType: 1,
        key: 0,
      };
      if (state.tacticType === 3) {
        lineData.step = 1;
        lineData.team = 1;
      }
      obj.details = [lineData];
    } else if (type === 'intraday') {
      // 日内
      obj.details = [];
      // if (state.tacticType === 1) {
      //     obj.details = [];
      // } else {
      //     const arr = hourOrder?.split('-');
      //     const lineData = {
      //         startOrder: arr?.[0] || '',
      //         endOrder: arr?.[1] || '',
      //         timePeriod: hourOrder,
      //         electricType: 1,
      //         key: 0,
      //     };
      //     if (state.tacticType === 3) {
      //         lineData.step = 1;
      //         lineData.endOrder = lineData.startOrder;
      //     }
      //     obj.details = [lineData];
      // }
    }
    data?.[+activeKey]?.strategyList?.push(obj);
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
    changeVisible();
  };

  return (
    <div className={styles.tactic_page}>
      {children ? (
        <>
          {!disabled && (
            <div className={styles.tactic_delete}>
              <img src={deleteTacticSvg} alt={''} onClick={deleteTacticFun} />
            </div>
          )}
          {title && <div className={styles.tactic_title}>{title}</div>}
          {children}
        </>
      ) : (
        <div className={styles.tactic_add}>
          {/* <img src={addTacticSvg} alt={''} onClick={changeVisible} /> */}
          <div className={styles.add_btn} onClick={changeVisible}>
            <PlusOutlined />
          </div>
          {state.visible && (
            <TJModel
              width={400}
              title={'新建策略'}
              onCancel={changeVisible}
              visible={state.visible}
              onOk={addTacticFun}
            >
              <div className={styles.tactic_add_content}>
                <div className={styles.tactic_add_content_title}>申报模板</div>
                <Select
                  style={{ width: 280 }}
                  options={state.options}
                  placeholder={'请选择内容'}
                  onSelect={tacticTypeChange}
                />
              </div>
            </TJModel>
          )}
        </div>
      )}
    </div>
  );
};

export default connect(({ global, interprovincialSpotDeclaration }) => ({
  planData: interprovincialSpotDeclaration.planData,
  activeKey: interprovincialSpotDeclaration.activeKey,
  type: interprovincialSpotDeclaration.type,
  selectRowsObj: interprovincialSpotDeclaration.selectRowsObj,
  date: interprovincialSpotDeclaration.date,
  hourOrder: interprovincialSpotDeclaration.hourOrder,
}))(TacticPage);
